Spiral Matrix

76

Spiral Matrix -

IList<int> PrintSpiralOrder(int[][] matrix)
{
  int hStart = 0;
  int hEnd = matrix[0].Length;
  int vEnd = matrix.Length;

  List<int> ans = new List<int>();

  while (hStart < hEnd && hStart < vEnd)
  {
    for (int i = hStart; i < hEnd; i++)
      ans.Add(matrix[hStart][i]);

    for (int j = hStart + 1; j < vEnd; j++)
      ans.Add(matrix[j][hEnd - 1]);

    if (hStart < vEnd - 1)
      for (int k = hEnd - 2; k >= hStart; k--)
        ans.Add(matrix[vEnd - 1][k]);

    if (hStart < hEnd - 1)
      for (int l = vEnd - 2; l >= hStart + 1; l--)//1>
        ans.Add(matrix[l][hStart]);

    hStart++;
    hEnd--;
    vEnd--;
  }

  return ans;
}

spiral matrix -

4
1 2 3 4 
5 6 7 8 
9 10 11 12
13 14 15 16

Comments

Submit
0 Comments